package beans.jdk7.filesystem;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

// 实现流程如下
// 1.为文件系统创建一个WatchService 实例 watcher
// 2.为你想监听的目录注册 watcher。注册时要注明监听那些事件。
// 3.在无限循环里面等待事件的触发。当一个事件发生时key发出信号并且加入到watcher的queue
// 4.从watcher的queue查找到key你可以从中获取到文件名等相关信息
// 5.遍历key的各种事件
// 6.重置 key重新等待事件
// 7.关闭服务
public class WatcherServiceTest
{
	private final WatchService watcher;

	public WatcherServiceTest(Path path) throws IOException
	{
		watcher = FileSystems.getDefault().newWatchService();
		path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
	}

	public void handleEvents() throws InterruptedException
	{
		while (true)
		{
			WatchKey key = watcher.take();
			for (WatchEvent<?> event : key.pollEvents())
			{
				Kind<?> kind = event.kind();
				if (kind == StandardWatchEventKinds.OVERFLOW)// 事件可能lost or discarded
				{
					continue;
				}
				@SuppressWarnings("unchecked")
				WatchEvent<Path> e = (WatchEvent<Path>) event;
				Path fileName = e.context();
				System.out.printf("Event %s has happened,which fileName is %s%n", kind.name(), fileName);

			}

			if (!key.reset())
			{
				break;
			}
		}
	}

	public static void main(String args[]) throws IOException, InterruptedException
	{
		// if (args.length != 1)
		// {
		// System.out.println("请设置要监听的文件目录作为参数");
		// System.exit(-1);
		// }
		new WatcherServiceTest(Paths.get("e:\\ftp")).handleEvents();
	}
	// 1.随便新建一个文件夹例如c:\\test
	// 2.运行程序java TestWatcherService c:\\test
	// 3.在该文件夹下新建一个文件本件“新建文本文档.txt”
	// 4.将上述文件改名为“abc.txt”
	// 5.打开文件输入点什么吧再保存。
	// 6.Over
	// 看看命令行输出的信息吧Event ENTRY_CREATE has happened,which fileName is 新建文本文档.txt
	// Event ENTRY_DELETE has happened,which fileName is 新建文本文档.txt
	// Event ENTRY_CREATE has happened,which fileName is abc.txt
	// Event ENTRY_MODIFY has happened,which fileName is abc.txt
	// Event ENTRY_MODIFY has happened,which fileName is abc.txt

}
